"""
试用 OpenCV 3.4.8 识别二维码的功能.

References:
- https://blog.csdn.net/kingroc/article/details/85265215
- opencv doc 3.4.8, cv::QRCodeDetector Class Reference
"""

import cv2
import numpy as np


def draw_vetices(img, bbox):
    """绘制opencv返回的二维码矩形信息"""
    n = len(bbox)
    
    for i in range(n):
        cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i+1)%n][0]), (255, 0, 0), 3)
        cv2.circle(img, tuple(bbox[i][0]), 6, (0, 0, 255), -1)


def try_detect_and_decode(img):
    """输入图片，输出二维码的值"""
    # retval: 二维码的值
    # points: 二维码四边形的顶点，在未找到二维码时为空
    # straight_qrcode: 拉直并二值化后的二维码图像
    qr = cv2.QRCodeDetector()
    retval, points, straight_qrcode = qr.detectAndDecode(im)
    
    # inspect returns
    print('retval:{}, type:{}'.format(retval, type(retval)))
    print('points type:{}, shape:{}'.format(type(points), points.shape))
    print('retimg type:{}, shape:{}'.format(type(straight_qrcode), straight_qrcode.shape))
    
    # view the results
    draw_vetices(img, points)
    cv2.imshow('straight_qrcode', straight_qrcode)
    cv2.imshow('quadrangle vertices', img)
    

def try_detect(img):
    """检查二维码，输入图片，输出二维码的位置(四个顶点)"""
    
    # retval: 一个布尔值，应该是找到二维码为True，没找到为False
    # points: 二维码四边形的顶点，在未找到二维码时为空
    qr = cv2.QRCodeDetector()
    # img[:] = 0  #  测试图片中没有二维码的结果
    retval, points = qr.detect(img)
    
    # inspect returns
    print('retval:{}, type:{}'.format(retval, type(retval)))
    print('points type:{}, shape:{}'.format(type(points), points.shape))
    
    # view the results
    draw_vetices(img, points)
    cv2.imshow('quadrangle vertices', img)


if __name__ == '__main__':
    
    im = cv2.imread(r'C:\_AAA\BlueNet\GK2020\design\experiments\qrcode/qr-11.png')
    
    # try_detect_and_decode(im)
    try_detect(im)
    
    
    while True:
        k = cv2.waitKey(10) & 0xFF
        
        if k == ord('q') or k == 27:
            break
    
